const generateFile = require('../utils/generateFile ');

const renderORMFile = (dbconf) => {
    console.log('--cur render orm config --', JSON.stringify(dbconf));
    return new Promise(async (resolve, reject) => {
        const tempFileContent = createContentTemp(dbconf);
        const { code } = await generateFile(`dist/orm/conn.js`, tempFileContent);
        if(code === 1) resolve({ code: 1, data: 'render conn.js successfully !'})
        else reject({ code : -1, data: 'render conn.js error !'});
    })
}

const createContentTemp = (dbconf) => {
    if(!dbconf) return new Error('no dbconf input createContentTemp error !') ;
    const { host, user, password, database, dialect, port } = dbconf;
    return  `const Sequelize = require('sequelize');

    module.exports = {
      // sequelize ORM 对象关系映射 
      connection: (req, res) => {
        const sequelize = new Sequelize(
          '${database}',
          '${user}',
          '${password}', 
          {
            dialect: '${dialect}',
            host: '${host}',
            port: ${port},
            define: {
              underscored: true,        // 字段以下划线（_）来分割（默认是驼峰命名风格）
              freezeTableName: true     // 冻结表名，停止自动复数命名
            },
            timezone: '+08:00'          // 东八区时间存储
          }
        )
        return sequelize;
      }
    }`
}

module.exports = renderORMFile
